'''
Created on Aug 22, 2011

@author: nktran
'''
import time
import urllib
import json

from xgoogle.search import GoogleSearch, SearchError

def get_number_results(query=""):
    """
    Return the number results for the query
    
    @return: number results
    """
    print query
    try:
        searcher = GoogleSearch(query, random_agent=True)
        number_results = searcher.num_results()
        print number_results
        return number_results
    except SearchError, e:
        print "Search failed: %s" % (e)
        
def get_results_with_googleapi(query=""):
    """
    """
    hits = 0
    print query
    try:
        query = urllib.urlencode({'q': query})
        url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
        search_response = urllib.urlopen(url)
        search_results = search_response.read()
        results = json.loads(search_results)
        data = results['responseData']
        if data != None and data['cursor'].has_key('estimatedResultCount'):
            hits = int(data['cursor']['estimatedResultCount'])        
    except:
        print "Error!"

    return hits
    
def search(query=""):
    """
    """        
    results = list()
    try:
        searcher = GoogleSearch(query, random_agent=True)
        for pid in range(5):
            searcher.page = pid
            searcher.results_per_page = 10            
            res = searcher.get_results()
            results.extend(res)                     
            time.sleep(5)
            
    except SearchError, e:
        print "Search failed: %s" % e
    
    return results

if __name__ == "__main__":
    print get_number_results('"Steve Jobs works for"')